layui.define(['layer', 'form', 'jquery'], function (exports) {

  var $ = layui.$,
      form = layui.form,
      layer = layui.layer,
      formData = null,
      expire = 0,
      miniPlusIsPick = false,
      uploader;
  var uploadwork = {

    init: function () {
      this.checkRealNameAuth();
      this.initData();
      this.initUploader();
      this.bindEvent();
    },
    checkRealNameAuth: function () {
      $.get('/copyright/realNameAuth/hasRealnameAuth', function (result) {
        if (result.success && !result.data) {
          layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            btn: ['确定'],
            btnAlign: 'c',
            skin: 'pe',
            area: ['500px', '260px'],
            content: $('.pop-edit'),
            yes: function (index, layero) {
              location.href = '/copyright/realname/authentication';
            },
          })
        }
      }, 'json')
    },
    initData: function () {
      var existWorks = Util.getQueryString("image");
      var localWorks;
      if(existWorks){
        var works = [];
        var workItem = {};
        workItem.fileName = 'image1';
        workItem.imageName = existWorks;
        works.push(workItem);
        localWorks = JSON.stringify(works);
      }else{
        localWorks = localStorage.getItem("worksFileInfo");
      }
      localStorage.removeItem('worksFileInfo');
      if (localWorks) {
        $(".plus").addClass('hide');
        works = JSON.parse(localWorks);
        for (var index in works) {
          var localWork = works[index];
          if (localWork.imageName) {
            var $plus_li = $('.mini-plus').parent(),
                $img_li = $($.parseHTML($('#img-block').html())),
                $img = $img_li.find('img'),
                $progress = $img_li.find('.layui-progress');
            $img.attr('src', localWork.imageName + '?x-oss-process=style/large_style_h');
            $img.show();
            $progress.addClass('hide');
            $img_li.find('h4').removeClass('hide').find('.img-title').html(
                localWork.fileName);
            $plus_li.parent('ul').show();
            $img_li.append('<input type="hidden" name="imageName" value="'
                + localWork.imageName
                + '"/>').append('<input type="hidden" name="fileName" value="' +
                localWork.fileName + '"/>');
            $img_li.insertBefore($plus_li);
          }
          if (localWork.epsImageName) {
            var $plus_li = $('.mini-plus').parent(),
                $img_li = $($.parseHTML($('#img-block').html())),
                $img = $img_li.find('img');
            $plus_li.parent('ul').show();
            $img_li.append('<input type="hidden" name="imageName" value="'
                + fileName
                + '.eps"/>').append('<input type="hidden" name="fileName" value="'
                +
                localWork.fileName + '"/>');
            $img_li.insertBefore($plus_li);
            $img_li.addClass("hide");
          }

        }
      }
    },
    bindEvent: function () {
      //点击删除作品
      $(document).on("click", ".container2 .body .c2-uploadarea li .opus h4 a",
          function () {
            var $image_li = $(this).parents('.image'),
                fileName = $image_li.find('input[name="imageName"]').val();
            $image_li.remove();
            var key = fileName.replace('http://meisudci.oss-cn-beijing.aliyuncs.com/','');
            if ($(".container2 .body .c2-uploadarea li").length <= 1) {
              $(".container2 .body .c2-uploadarea ul").hide();
              $(".container2 .body .plus").removeClass('hide');
              uploader.reset();
            }
            $.get('/oss/deleteObject', {key: key});
            return false;
          })

      form.on('submit(*)', function (data) {
        if (uploader.isInProgress()) {
          layer.msg('文件正在上传中');
          return false;
        }

        var works = [];
        for (var index = 0; index < $('.images-ul li.image').length; index++) {
          var result = $('.images-ul li.image')[index];
          var imageName = $(result).find('input[name="imageName"]').val(),
              fileName = $(result).find('input[name="fileName"]').val(),
              fileRealName = fileName.substring(0, fileName.lastIndexOf('.')),
              fileExt = fileName.substring(fileName.lastIndexOf('.') + 1,
                  fileName.length);

          var workInfo = {};

          var flag = false;
          for (var subIndex in works) {
            var winfo = works[subIndex];
            if (winfo.fileName == fileRealName) {
              if (fileExt == 'eps') {
                winfo.epsImageName = imageName;
              } else {
                winfo.imageName = imageName;
              }
              flag = true;
              break;
            }

          }

          if (flag) {
            continue;
          }
          workInfo.fileName = fileRealName;
          if (fileExt == 'eps') {
            workInfo.epsImageName = imageName;
          } else {
            workInfo.imageName = imageName;
          }
          works.push(workInfo);
        }

        console.log(works);
        localStorage.setItem("worksFileInfo", JSON.stringify(works));
        location.href = '/copyright/register/edit';
        return false;
      });

    },
    initUploader: function () {
      var that = this;
      uploader = WebUploader.create({

        // swf文件路径
        swf: '/static/front/webuploader/Uploader.swf',
        compress: false,
        auto: true,

        thumb: {
          width: 336,
          height: 202,

          // 图片质量，只有type为`image/jpeg`的时候才有效。
          quality: 100,

          // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
          allowMagnify: true,

          // 是否允许裁剪。
          crop: false,

          fileNumLimit: 20,

        },

        // 文件接收服务端。
        server: 'http://meisudci.oss-cn-beijing.aliyuncs.com',
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '.plus',

        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false,
        accept: {
          title: 'Images',
          extensions: 'gif,jpg,jpeg,bmp,png,eps',
          mimeTypes: 'image/jpg,image/gif,image/jpeg,image/png,image/bmp,application/postscript'
        },
      });
      //文件添加到容器
      uploader.on('fileQueued', function (file) {
        var ext = file.ext;
        $(".plus").addClass('hide');
        var $plus_li = $('.mini-plus').parent(),
            $img_li = $($.parseHTML($('#img-block').html())),
            $img = $img_li.find('img');
        uploader.makeThumb(file, function (error, ret) {
          if (error) {
            $img.text('预览错误');
          } else {
            $img.attr('src', ret);
            $img.show();
          }
        });
        if(!miniPlusIsPick){
          miniPlusIsPick = true;
          uploader.addButton({id:'.mini-plus'});
        }
        $plus_li.parent('ul').show();
        $img_li.attr('id', file.id);
        $img_li.insertBefore($plus_li);
        if (ext == 'eps') {
          $img.attr('src', '/static/front/imgs/backImage.png');
        }
      });

      // 文件上传过程中创建进度条实时显示。
      uploader.on('uploadProgress', function (file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.layui-progress .layui-progress-bar');
        $percent.css('width', percentage * 100 + '%');
      });

      uploader.on('uploadBeforeSend', function (obj, data, headers) {
        that.getSignure();
        var fileName = Util.nuid() + "." +obj.file.ext,
            $li = $('#' + obj.file.id);
        formData.key = formData.dir + "/" + fileName;
        $.extend(data, formData);
        var fileUrl = "http://meisudci.oss-cn-beijing.aliyuncs.com/" + formData.key;
        $li.append('<input type="hidden" name="imageName" value="' + fileUrl
            + '"/>').append('<input type="hidden" name="fileName" value="' +
            obj.file.name + '"/>');
      });

      uploader.on('uploadSuccess', function (file, response) {
        var $li = $('#' + file.id),
            $progress = $li.find('.layui-progress');
        $progress.addClass('hide');
        $li.find('h4').removeClass('hide');
        $li.find('.img-title').html(file.name);
        var creationDate;
        if(typeof (file.lastModifiedDate)=='string'){
          creationDate = Util.dateFormat(new Date(),'YYYY-MM-dd');
        }else{
          creationDate = Util.dateFormat(file.lastModifiedDate, 'YYYY-MM-dd');
        }
        localStorage.setItem('creationDate', creationDate);
      })

    },
    getSignure: function () {
      now = timestamp = Date.parse(new Date()) / 1000;
      if (expire < now + 3000) {
        $.ajax({
              url: '/oss/getWorksPolicy',
              dataType: 'json',
              async: false,
              success: function (result) {
                if (result.success) {
                  formData = $.extend(formData, result.data);
                  formData.success_action_status = "200";
                  formData.OSSAccessKeyId = result.data.accessid;
                  expire = result.expire;
                }
              }
            }
        )
      }
    }
  }
  uploadwork.init();
  exports('uploadwork', {});
});